import axios from "axios";
// 网页状态进度条
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import type {
  AxiosRequestConfig,
  AxiosResponse,
  AxiosError,
  AxiosPromise,
  InternalAxiosRequestConfig,
} from "axios";
const { BASE_URL } = process.env;
const server = axios.create({
  baseURL: BASE_URL,
  timeout: 5000,
});
// 请求拦截器
server.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    NProgress.start();
    return config;
  },
  (error: AxiosError) => {
    console.log("请求出错：", error);
  }
);

// 响应拦截器
server.interceptors.response.use(
  (response: AxiosResponse) => {
    NProgress.done();
    const status = response.status;
    if (status === 200) {
      return Promise.resolve(response.data);
    } else {
      return Promise.reject(response.data);
    }
  },
  (error: AxiosError) => {
    console.log("响应出错：", error);
  }
);
// 后续其他问题改造封装
type Methods = "GET" | "POST" | "PUT" | "DELETE";
function http(
  method: Methods = "GET",
  url: string,
  data?: { [key: string]: any },
  config: AxiosConfig = {}
) {
  const data_flag = method === "GET" ? true : false;
  const request_config: AxiosRequestConfig = {
    method,
    url,
    params: data_flag ? data : {},
    data: data_flag ? {} : data,
    ...config,
  };
  return server(request_config);
}
type AxiosConfig = Omit<
  AxiosRequestConfig,
  "url" | "method" | "params" | "data"
>;
/** Axios 二次封装 */
export default class AxiosRequest {
  static get(
    url: string,
    data: { [key: string]: any } = {},
    config: AxiosConfig = {}
  ): AxiosPromise<any> {
    return http("GET", url, data, config);
  }
  static post(
    url: string,
    data: { [key: string]: any } = {},
    config: AxiosConfig = {}
  ): AxiosPromise<any> {
    return http("POST", url, data, config);
  }
  static put(
    url: string,
    data: { [key: string]: any } = {},
    config: AxiosConfig = {}
  ): AxiosPromise<any> {
    return http("PUT", url, data, config);
  }
  static delete(
    url: string,
    data: { [key: string]: any } = {},
    config: AxiosConfig = {}
  ): AxiosPromise<any> {
    return http("DELETE", url, data, config);
  }
}
